package Controllers;

import Information.PostInfo;
import Information.UserInfo;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import java.io.*;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.application.Application;
import javafx.fxml.Initializable;

import static Application.ReadFileToString.readFile;


public class CollectionController extends Application implements Initializable {

    private UserInfo userInfo;

    @FXML
    private VBox vbox;

    //---------------------收藏夹界面初始化---------------------------------
    @Override
    public void start(Stage primaryStage) {
        try {
            AnchorPane root = FXMLLoader.load(getClass().getResource("../Resources/Collection.fxml"));
            Scene scene = new Scene(root, 700.0, 800.0);
            //scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.getIcons().add(new Image("/Images/logoblue.png"));
            primaryStage.setTitle("收藏界面");
            primaryStage.setScene(scene);
            primaryStage.setResizable(false);
            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getdate() {
        try (
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/UserPosts/currentUser.ser"))) {
            try {
                userInfo = (UserInfo) ois.readObject();
            } catch (ClassNotFoundException e) {
                System.out.println(4);
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < userInfo.getCollectPostID().size(); i++) {
            //针对收藏数组内的帖子建立对应的Borderpane并插入vbox
            File k = new File("src/UserPosts/postObjects/" + userInfo.getCollectPostID().get(i) + ".ser");
            if(!k.exists()){
                userInfo.getCollectPostID().remove(userInfo.getCollectPostID().get(i));
                try(
                        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/UserPosts/userObjects/"+ userInfo.getId()+".ser")))
                {
                    oos.writeObject(userInfo);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try(
                        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/UserPosts/currentUser.ser")))
                {
                    oos.writeObject(userInfo);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                continue;
            }else {
                System.out.println(userInfo.getCollectPostID().get(i));
                File a = new File("src/UserPosts/postTitles/" + userInfo.getCollectPostID().get(i) + ".txt");
                if (!a.exists()) {
                    userInfo.getCollectPostID().remove(userInfo.getCollectPostID().get(i));
                    try (
                            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/UserPosts/userObjects/" + userInfo.getId() + ".ser"))) {
                        oos.writeObject(userInfo);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try (
                            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/UserPosts/currentUser.ser"))) {
                        oos.writeObject(userInfo);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    continue;

                }
            }
            vbox.getChildren().addAll(CreatePost(userInfo.getCollectPostID().get(i)), new Separator());
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        getdate();
    }
    //------------------------------------初始化结束-------------------------------------------------


    //--------------------------实现收藏夹功能--------------------------------------------
    public BorderPane CreatePost(String PostIDCollection) {
        BorderPane borderPane = new BorderPane();
        PostInfo postInfo = null;
        try (
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/UserPosts/postObjects/" + PostIDCollection + ".ser"))) {
            try {
                postInfo = (PostInfo) ois.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            //对收藏夹内的帖子标题进行设置

            assert postInfo != null;
            String title = readFile(postInfo.getTitlePath());
            Label Postname = new Label(title);
            Postname.setPrefSize(250,80);
            Postname.setWrapText(true);
            Postname.setFont(Font.font("Agency FB", 23));
            Postname.setTranslateY(10);
            Postname.setTranslateX(10);

            //点击帖子名时打开相关帖子的事件设置
            PostInfo finalPostInfo = postInfo;
            Postname.setOnMouseClicked(event -> {
                try {
                    toPostSite(finalPostInfo);
                }catch (Exception e){
                    e.printStackTrace();
                }
            });

            //如果有图片，则显示，若无，则显示空图片
            if(new File(postInfo.getImg()).exists()){
                 Image image = new Image("file:"+postInfo.getImg());
                 ImageView Postpicture = new ImageView();
                 Postpicture.setImage(image);
                 Postpicture.setFitHeight(90.0);
                 Postpicture.setFitWidth(136.0);
                 Postpicture.setTranslateX(-10);
                 Postpicture.setTranslateY(10);
                 borderPane.setRight(Postpicture);
            } else{
                ImageView Postpicture = new ImageView();
                Postpicture.setFitHeight(90.0);
                Postpicture.setFitWidth(136.0);
                borderPane.setRight(Postpicture);
            }


            //设置信息栏
            Label PostMessage = new Label( postInfo.getCreatedTime()+'\t'+postInfo.getTag());
            PostMessage.setFont(Font.font("System", 16));

            //调节信息栏的位置
            PostMessage.setTranslateX(10);

            //将所有构件加进borderpane
            borderPane.setLeft(Postname);
            borderPane.setBottom(PostMessage);
            borderPane.setPrefHeight(100);


        } catch (IOException e) {
            e.printStackTrace();
        }
        return borderPane;
    }

    public void toPostSite(PostInfo postInfo) {
        if(postInfo != null){
            //打开帖子详情
            try(
                    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/UserPosts/currentPost.ser")))
            {   //写入当前帖子对象
                oos.writeObject(postInfo);
            } catch (IOException e) {
                e.printStackTrace();
            }
            PostSiteController postSite = new PostSiteController();//打开帖子详情页
            postSite.start(new Stage());
        }
    }
}
